<template>
  <div class="dashboard">
    <!-- 数据概览卡片 -->
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card class="data-card">
          <template #header>
            <div class="card-header">
              <span>总用户数</span>
              <el-icon><User /></el-icon>
            </div>
          </template>
          <div class="card-value">{{ statistics.totalUsers }}</div>
          <div class="card-footer">
            <span>今日新增：{{ statistics.newUsers }}</span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="data-card">
          <template #header>
            <div class="card-header">
              <span>总商品数</span>
              <el-icon><Goods /></el-icon>
            </div>
          </template>
          <div class="card-value">{{ statistics.totalProducts }}</div>
          <div class="card-footer">
            <span>今日新增：{{ statistics.newProducts }}</span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="data-card">
          <template #header>
            <div class="card-header">
              <span>总订单数</span>
              <el-icon><List /></el-icon>
            </div>
          </template>
          <div class="card-value">{{ statistics.totalOrders }}</div>
          <div class="card-footer">
            <span>今日新增：{{ statistics.newOrders }}</span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="data-card">
          <template #header>
            <div class="card-header">
              <span>总积分发放</span>
              <el-icon><Trophy /></el-icon>
            </div>
          </template>
          <div class="card-value">{{ statistics.totalPoints }}</div>
          <div class="card-footer">
            <span>本月发放：{{ statistics.monthlyPoints }}</span>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 第二行统计卡片 -->
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card class="data-card">
          <template #header>
            <div class="card-header">
              <span>总留言数</span>
              <el-icon><ChatDotRound /></el-icon>
            </div>
          </template>
          <div class="card-value">{{ statistics.totalMessages }}</div>
          <div class="card-footer">
            <span>今日新增：{{ statistics.newMessages }}</span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="data-card">
          <template #header>
            <div class="card-header">
              <span>总销售额</span>
              <el-icon><Money /></el-icon>
            </div>
          </template>
          <div class="card-value">¥{{ statistics.totalSales }}</div>
          <div class="card-footer">
            <span>本月销售：¥{{ statistics.monthlySales }}</span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="data-card">
          <template #header>
            <div class="card-header">
              <span>平均订单金额</span>
              <el-icon><TrendCharts /></el-icon>
            </div>
          </template>
          <div class="card-value">¥{{ statistics.avgOrderAmount }}</div>
          <div class="card-footer">
            <span>较上月：{{ statistics.orderAmountChange }}%</span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="data-card">
          <template #header>
            <div class="card-header">
              <span>用户活跃度</span>
              <el-icon><DataLine /></el-icon>
            </div>
          </template>
          <div class="card-value">{{ statistics.activeUsers }}%</div>
          <div class="card-footer">
            <span>较上月：{{ statistics.activeUsersChange }}%</span>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>最近7天订单趋势</span>
            </div>
          </template>
          <div class="chart-container">
            <div ref="orderChartRef" class="chart"></div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>用户等级分布</span>
            </div>
          </template>
          <div class="chart-container">
            <div ref="userLevelChartRef" class="chart"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 第二行图表 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>商品分类统计</span>
            </div>
          </template>
          <div class="chart-container">
            <div ref="categoryChartRef" class="chart"></div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>积分发放趋势</span>
            </div>
          </template>
          <div class="chart-container">
            <div ref="pointsChartRef" class="chart"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 最新动态 -->
    <el-row :gutter="20" class="activity-row">
      <el-col :span="12">
        <el-card class="activity-card">
          <template #header>
            <div class="card-header">
              <span>最新订单</span>
              <el-button link @click="$router.push('/admin/orders')">查看更多</el-button>
            </div>
          </template>
          <el-table :data="latestOrders" style="width: 100%">
            <el-table-column prop="orderNumber" label="订单号" width="150" />
            <el-table-column prop="user.username" label="用户名" width="100" />
            <el-table-column prop="totalAmount" label="金额" width="80">
              <template #default="{ row }">
                ¥{{ row.totalAmount }}
              </template>
            </el-table-column>
            <el-table-column prop="orderPoints" label="积分" width="60">
              <template #default="{ row }">
                {{ row.orderPoints }}
              </template>
            </el-table-column>
            <el-table-column prop="orderStatus" label="状态" width="80">
              <template #default="{ row }">
                <el-tag :type="getStatusType(row.orderStatus)">
                  {{ getStatusText(row.orderStatus) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="orderDate" label="创建时间" width="120">
              <template #default="{ row }">
                {{ formatDate(row.orderDate) }}
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="activity-card">
          <template #header>
            <div class="card-header">
              <span>最新留言</span>
              <el-button link @click="$router.push('/admin/messages')">查看更多</el-button>
            </div>
          </template>
          <div class="message-list">
            <div v-for="message in latestMessages" :key="message.id" class="message-item">
              <div class="message-header">
                <span class="username">{{ message.user?.username }}</span>
                <span class="time">{{ formatDate(message.createTime) }}</span>
              </div>
              <div class="message-content">{{ message.content }}</div>
              <div v-if="message.isReplied" class="message-reply">
                <span class="reply-label">回复：</span>
                <span class="reply-content">{{ message.reply }}</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { User, Goods, List, ChatDotRound, Trophy, Money, TrendCharts, DataLine } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { getStatistics, getLatestOrders, getLatestMessages } from '@/api/admin'

// 统计数据
const statistics = ref({
  totalUsers: 0,
  newUsers: 0,
  totalProducts: 0,
  newProducts: 0,
  totalOrders: 0,
  newOrders: 0,
  totalMessages: 0,
  newMessages: 0,
  totalPoints: 0,
  monthlyPoints: 0,
  totalSales: 0,
  monthlySales: 0,
  avgOrderAmount: 0,
  orderAmountChange: 0,
  activeUsers: 0,
  activeUsersChange: 0
})

// 最新订单和留言
const latestOrders = ref([])
const latestMessages = ref([])

// 图表实例
let orderChart = null
let userLevelChart = null
let categoryChart = null
let pointsChart = null
const orderChartRef = ref(null)
const userLevelChartRef = ref(null)
const categoryChartRef = ref(null)
const pointsChartRef = ref(null)

// 加载统计数据
const loadStatistics = async () => {
  try {
    const res = await getStatistics()
    statistics.value = res.data
  } catch (error) {
    console.error(error)
  }
}

// 加载最新订单
const loadLatestOrders = async () => {
  try {
    const res = await getLatestOrders()
    latestOrders.value = res.data
  } catch (error) {
    console.error(error)
  }
}

// 加载最新留言
const loadLatestMessages = async () => {
  try {
    const res = await getLatestMessages()
    latestMessages.value = res.data
  } catch (error) {
    console.error(error)
  }
}

// 初始化订单趋势图表
const initOrderChart = () => {
  orderChart = echarts.init(orderChartRef.value)
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '订单数',
        type: 'line',
        smooth: true,
        data: [120, 132, 101, 134, 90, 230, 210]
      },
      {
        name: '销售额',
        type: 'line',
        smooth: true,
        data: [12000, 13200, 10100, 13400, 9000, 23000, 21000]
      }
    ]
  }
  orderChart.setOption(option)
}

// 初始化用户等级分布图表
const initUserLevelChart = () => {
  userLevelChart = echarts.init(userLevelChartRef.value)
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '用户等级',
        type: 'pie',
        radius: '50%',
        data: [
          { value: 150, name: '普通会员' },
          { value: 80, name: '银卡会员' },
          { value: 50, name: '金卡会员' },
          { value: 20, name: '钻石会员' }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  userLevelChart.setOption(option)
}

// 初始化商品分类图表
const initCategoryChart = () => {
  categoryChart = echarts.init(categoryChartRef.value)
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '商品分类',
        type: 'pie',
        radius: '50%',
        data: [
          { value: 1048, name: '电子产品' },
          { value: 735, name: '服装' },
          { value: 580, name: '食品' },
          { value: 484, name: '图书' },
          { value: 300, name: '家居' },
          { value: 200, name: '运动' },
          { value: 150, name: '美妆' }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  categoryChart.setOption(option)
}

// 初始化积分发放趋势图表
const initPointsChart = () => {
  pointsChart = echarts.init(pointsChartRef.value)
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '积分发放',
        type: 'bar',
        data: [12000, 15000, 18000, 22000, 25000, 28000]
      }
    ]
  }
  pointsChart.setOption(option)
}

// 工具函数
const formatDate = (date) => {
  return new Date(date).toLocaleString()
}

const getStatusType = (status) => {
  const types = {
    PENDING: 'warning',
    PAID: 'info',
    SHIPPED: 'primary',
    DELIVERED: 'success',
    COMPLETED: 'success',
    CANCELLED: 'danger'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    PENDING: '待付款',
    PAID: '已付款',
    SHIPPED: '已发货',
    DELIVERED: '已送达',
    COMPLETED: '已完成',
    CANCELLED: '已取消'
  }
  return texts[status] || status
}

// 监听窗口大小变化，重绘图表
const handleResize = () => {
  if (orderChart) orderChart.resize()
  if (userLevelChart) userLevelChart.resize()
  if (categoryChart) categoryChart.resize()
  if (pointsChart) pointsChart.resize()
}

onMounted(async () => {
  await loadStatistics()
  await loadLatestOrders()
  await loadLatestMessages()
  initOrderChart()
  initUserLevelChart()
  initCategoryChart()
  initPointsChart()

  // 监听窗口大小变化，重绘图表
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  // 移除窗口大小变化监听器
  window.removeEventListener('resize', handleResize)
  
  // 销毁图表实例
  if (orderChart) {
    orderChart.dispose()
    orderChart = null
  }
  if (userLevelChart) {
    userLevelChart.dispose()
    userLevelChart = null
  }
  if (categoryChart) {
    categoryChart.dispose()
    categoryChart = null
  }
  if (pointsChart) {
    pointsChart.dispose()
    pointsChart = null
  }
})
</script>

<style scoped>
.dashboard {
  padding: 20px;
}

.data-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin: 10px 0;
}

.card-footer {
  font-size: 14px;
  color: #909399;
}

.chart-row {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-container {
  height: 300px;
}

.chart {
  width: 100%;
  height: 100%;
}

.activity-card {
  margin-bottom: 20px;
}

.message-list {
  max-height: 400px;
  overflow-y: auto;
}

.message-item {
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}

.message-item:last-child {
  border-bottom: none;
}

.message-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

.username {
  font-weight: bold;
  color: #303133;
}

.time {
  color: #909399;
  font-size: 14px;
}

.message-content {
  color: #606266;
  line-height: 1.6;
  margin-bottom: 5px;
}

.message-reply {
  background-color: #f5f7fa;
  padding: 8px;
  border-radius: 4px;
  margin-top: 5px;
}

.reply-label {
  font-weight: bold;
  color: #409eff;
}

.reply-content {
  color: #606266;
}
</style> 